package com.ec.gateway.utils;

import com.ec.gateway.common.enums.RespResultEnum;
import com.ec.gateway.exception.CheckJwtException;
import com.google.common.base.Charsets;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;

import java.util.Base64;
import java.util.Objects;

/**
 * <p>
 *
 * </p >
 *
 * @author Eric Lee
 * @since 2022-05-03 23:31
 */
@Component
public class JwtUtil {
    private static final String JWT_SECRET_KEY_PROP_KEY = "ec.jwt-secretKey";

    /**
     * 解析 token信息
     *
     * @param jsonWebToken
     * @return
     */
    public static Claims parseJwt(String jsonWebToken) {
        return parseJwt(jsonWebToken, JWT_SECRET_KEY_PROP_KEY);
    }

    /**
     * @param jsonWebToken
     * @param secretKey    密钥
     * @return
     */
    public static Claims parseJwt(String jsonWebToken, String secretKey) {
        try {
            byte[] decodeKey = Base64.getDecoder().decode(getBase64Security(secretKey));
            return Jwts.parser().setSigningKey(decodeKey).parseClaimsJws(jsonWebToken).getBody();
        } catch (ExpiredJwtException expired) {
            throw new CheckJwtException(RespResultEnum.TOKEN_EXPIRED_ERROR.getCode(), RespResultEnum.TOKEN_EXPIRED_ERROR.getMessage());
        } catch (Exception e) {
            throw new CheckJwtException(RespResultEnum.TOKEN_CHECK_INVALID_ERROR.getCode(), RespResultEnum.TOKEN_EXPIRED_ERROR.getMessage());
        }
    }

    private static String getBase64Security(String secretKey){
        String jwtSecretKey = JWT_SECRET_KEY_PROP_KEY;
        if(!Objects.isNull(secretKey)) {
            jwtSecretKey = secretKey;
        }
        return Base64.getEncoder().encodeToString(jwtSecretKey.getBytes(Charsets.UTF_8));
    }
}